package first.group.ssh.packet;

import first.group.ssh.SSHConsts;
import first.group.ssh.packet.reader.BooleanReader;
import first.group.ssh.packet.reader.StringReader;
import first.group.ssh.packet.writer.BooleanWriter;
import first.group.ssh.packet.writer.StringWriter;
import java.nio.ByteBuffer;

public class DebugPacket extends Packet{
    public final boolean alwaysDisplay;
    public final String message;
    public final String language;

    public DebugPacket(boolean alwaysDisplay, String message, String language) {
        super(SSHConsts.SSH_MSG_DEBUG);
        this.alwaysDisplay = alwaysDisplay;
        this.message = message;
        this.language = language;
    }

    public static PacketParser<DebugPacket> PARSER = new DebugPacket.Parser();

    private static class Parser extends PacketParser<DebugPacket> {

        @Override
        public DebugPacket parse(ByteBuffer buffer) {
            var alwaysDisplay = BooleanReader.readBoolean(buffer);
            if (alwaysDisplay == null) {
                return null;
            }
            var message = StringReader.readString(buffer);
            if (message == null) {
                return null;
            }
            var language = StringReader.readString(buffer);
            if (language == null) {
                return null;
            }
            return new DebugPacket(alwaysDisplay, message, language);
        }
    }

    @Override
    public void write(ByteBuffer buffer) {
        BooleanWriter.writeBoolean(buffer, alwaysDisplay);
        var writeMessage = message.replace("\n", "\r\n");
        StringWriter.writeString(buffer, writeMessage);
        StringWriter.writeString(buffer, language);
    }
    
    public String getMessage() {
        return message.replace("\r\n", "\n");
    }
}
